package com.compass.mobile.ui.activity

import UserInfoManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.compass.mobile.R
import com.compass.mobile.callback.OnCustomButtonClick
import com.compass.mobile.databinding.ActivityIntelligentGuidanceBinding
import com.compass.mobile.framework.base.BaseVBActivity
import com.compass.mobile.framework.ext.onClick
import com.compass.mobile.framework.utils.DateUtils
import com.compass.mobile.framework.utils.FullyGridLayoutManager
import com.compass.mobile.models.AIMessageInfo
import com.compass.mobile.models.AiData
import com.compass.mobile.models.CommonBean
import com.compass.mobile.ui.adapter.AIMessageAdapter
import com.compass.mobile.ui.adapter.CommonAdapter
import com.compass.mobile.ui.viewModel.IntelligentGuidanceViewModel
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent

/**
 * Description： 智能导诊
 * Date:2024/7/1 13:45
 */
class IntelligentGuidanceActivity : BaseVBActivity<ActivityIntelligentGuidanceBinding>() {

    private val intelligentGuidanceViewModel: IntelligentGuidanceViewModel by viewModels()
    private var event = "session_start"//首次

    private var aiData: AiData? = null
    private lateinit var aiAdapter: AIMessageAdapter//消息
    private lateinit var commonAdapter: CommonAdapter//常见症状
    private val TYPE_RECEIVED: Int = 0//接收
    private val TYPE_SEND: Int = 1//发送
    private val TYPE_TEXT: Int = 0//是文字类型
    private val TYPE_DEPT: Int = 1//是科室
    private var aiMsg: MutableList<AIMessageInfo> = mutableListOf()
    private var aiCommonList: MutableList<CommonBean> = mutableListOf()
    private var selectedList: MutableList<String> = mutableListOf()

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, IntelligentGuidanceActivity::class.java)
            context.startActivity(intent)
        }
    }


    private var onBottomClick = object : OnCustomButtonClick {
        override fun onButtonCallBack(codeType: Int, id: String?) {
            if (codeType == 2) {
                id?.let {
                    DepartmentIntroductionActivity.start(
                        this@IntelligentGuidanceActivity,
                        it,null,
                        "inquiry"
                    )
                }
            }
        }
    }


    override fun initView(savedInstanceState: Bundle?) {
        aiAdapter = AIMessageAdapter()
        commonAdapter = CommonAdapter()
        mBinding.recyclerView.apply {
            layoutManager =
                LinearLayoutManager(
                    this@IntelligentGuidanceActivity,
                    LinearLayoutManager.VERTICAL,
                    false
                )
            adapter = aiAdapter
        }
        aiAdapter.setBottomCallBack(onBottomClick)

        mBinding.edtKeyWords.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEND) {
                val text = mBinding.edtKeyWords.text.toString().trim()
                sendMessage(text)
            }
            false
        }
        mBinding.rcyCommon.apply {
            val layoutFelManager = FlexboxLayoutManager(context)
            layoutFelManager.flexWrap = FlexWrap.WRAP // 按正常方向换行
            layoutFelManager.flexDirection = FlexDirection.ROW // 水平方向
            layoutFelManager.justifyContent = JustifyContent.FLEX_START // 左对齐
            layoutManager = layoutFelManager
            itemAnimator?.let {
                (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
            }
            adapter = commonAdapter
        }

        commonAdapter.onItemClickListener = { _: View, p: Int ->
            val item = commonAdapter.getItem(p)

            item?.let {
                sendSelectMessage(item.option)
                selectedList.clear()
                event = "department_suggestion_select" //左侧选择时的event
                selectedList.add(it.option)
                aiData = AiData(selected = selectedList)
                intelligentGuidanceViewModel.intelligentGuidance(event, aiData)
            }
        }


    }

    override fun initData() {
        aiData = AiData(
            DateUtils.formatAgeToNumber(UserInfoManager.getPatientInfo()?.birthday),
            UserInfoManager.getPatientInfo()?.sex
        )
        intelligentGuidanceViewModel.commonSymptoms(
            DateUtils.formatAgeToNumber(UserInfoManager.getPatientInfo()?.birthday),
            UserInfoManager.getPatientInfo()?.sex
        )
        intelligentGuidanceViewModel.intelligentGuidance(event, aiData)
        intelligentGuidanceViewModel.aiDataLiveData.observe(this) {

            it?.let {
                //session_end 首次event  part_symptoms 出错event   department_suggestion_select选择event  统一重置为department_suggestion_input
                event = if (it.next_event == "session_end" || it.next_event == "part_symptoms"||it.next_event=="department_suggestion_select") {
                    "department_suggestion_input"
                } else {
                    it.next_event
                }

                it.message.departments?.let { list ->
                    for (dept in list) {
                        aiMsg.add(AIMessageInfo(TYPE_DEPT, null, TYPE_RECEIVED, dept))
                    }
                } ?: kotlin.run {
                    for (msg in it.message.text) {
                        aiMsg.add(AIMessageInfo(TYPE_TEXT, msg, TYPE_RECEIVED, null))
                    }

                }

                aiAdapter.setData(aiMsg)
                moveBottom()

            }
        }
        intelligentGuidanceViewModel.commonListLiveData.observe(this) {
            it?.let {
                aiCommonList = it
                commonAdapter.setData(aiCommonList)
            }

        }
    }

    override fun intListener() {
        mBinding.sendButton.onClick {
            val text = mBinding.edtKeyWords.text.toString().trim()
            sendMessage(text)
        }
        mBinding.tvWrittenConsent.onClick {


        }
    }


    /**
     * 发送消息并
     */
    private fun sendMessage(text: String) {
//        val text = "我的头痛，腹痛挂什么科室"
        if (text.isEmpty()) {
            showToast("请输入要咨询的内容")
            return
        }

        aiMsg.add(AIMessageInfo(TYPE_TEXT, text, TYPE_SEND, null))//添加消息到adapter
        aiAdapter.addItem(AIMessageInfo(TYPE_TEXT, text, TYPE_SEND, null))
        mBinding.edtKeyWords.setText("")
        aiData = AiData(text = text)
        intelligentGuidanceViewModel.intelligentGuidance(event, aiData)
    }


    /**
     * 发送选择消息并
     */
    private fun sendSelectMessage(text: String) {
        aiMsg.add(AIMessageInfo(TYPE_TEXT, text, TYPE_SEND, null))//添加消息到adapter
        aiAdapter.addItem(AIMessageInfo(TYPE_TEXT, text, TYPE_SEND, null))


    }


    private fun moveBottom() {
        val position = aiAdapter.getData().size - 1
        mBinding.recyclerView.scrollToPosition(position)

    }
}